/*
  +----------------------------------------------------------------------+
  | PHP Version 5                                                        |
  +----------------------------------------------------------------------+
  | Copyright (c) 1997-2007 The PHP Group                                |
  +----------------------------------------------------------------------+
  | This source file is subject to version 3.01 of the PHP license,      |
  | that is bundled with this package in the file LICENSE, and is        |
  | available through the world-wide-web at the following url:           |
  | http://www.php.net/license/3_01.txt                                  |
  | If you did not receive a copy of the PHP license and are unable to   |
  | obtain it through the world-wide-web, please send a note to          |
  | license@php.net so we can mail you a copy immediately.               |
  +----------------------------------------------------------------------+
  | Author: zhigang zhang <zhangzhigang@openv.cn>                        |
  +----------------------------------------------------------------------+
*/

/* $Id: header 226204 2007-01-01 19:32:10Z iliaa $ */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include "php.h"
#include "php_ini.h"
#include "ext/standard/info.h"
#include "php_consistent_hash.h"
#include "consistent_hash.h"

/* If you declare any globals in php_consistent_hash.h uncomment this:
ZEND_DECLARE_MODULE_GLOBALS(consistent_hash)
*/

/* True global resources - no need for thread safety here */

#define le_chash_name "CHash Handle"
int le_chash;
static zval * nearest_rid;
static int le_consistent_hash;

/* {{{ consistent_hash_functions[]
 *
 * Every user visible function must have an entry in consistent_hash_functions[].
 */
zend_function_entry consistent_hash_functions[] = {
	PHP_FE(confirm_consistent_hash_compiled,	NULL)		/* For testing, remove later. */
	PHP_FE(consistent_hash_init,	NULL)		/* consistent hash table init*/
	PHP_FE(consistent_hash_lookup, NULL) /*consistent hash lookuping*/
	{NULL, NULL, NULL}	/* Must be the last line in consistent_hash_functions[] */
};
/* }}} */

/* {{{ consistent_hash_module_entry
 */
zend_module_entry consistent_hash_module_entry = {
#if ZEND_MODULE_API_NO >= 20010901
	STANDARD_MODULE_HEADER,
#endif
	"consistent_hash",
	consistent_hash_functions,
	PHP_MINIT(consistent_hash),
	PHP_MSHUTDOWN(consistent_hash),
	PHP_RINIT(consistent_hash),		/* Replace with NULL if there's nothing to do at request start */
	PHP_RSHUTDOWN(consistent_hash),	/* Replace with NULL if there's nothing to do at request end */
	PHP_MINFO(consistent_hash),
#if ZEND_MODULE_API_NO >= 20010901
	"0.1", /* Replace with version number for your extension */
#endif
	STANDARD_MODULE_PROPERTIES
};
/* }}} */

#ifdef COMPILE_DL_CONSISTENT_HASH
ZEND_GET_MODULE(consistent_hash)
#endif

/* {{{ PHP_INI
 */
/* Remove comments and fill if you need to have entries in php.ini
PHP_INI_BEGIN()
    STD_PHP_INI_ENTRY("consistent_hash.global_value",      "42", PHP_INI_ALL, OnUpdateLong, global_value, zend_consistent_hash_globals, consistent_hash_globals)
    STD_PHP_INI_ENTRY("consistent_hash.global_string", "foobar", PHP_INI_ALL, OnUpdateString, global_string, zend_consistent_hash_globals, consistent_hash_globals)
PHP_INI_END()
*/
/* }}} */

/* {{{ php_consistent_hash_init_globals
 */
/* Uncomment this function if you have INI entries
static void php_consistent_hash_init_globals(zend_consistent_hash_globals *consistent_hash_globals)
{
	consistent_hash_globals->global_value = 0;
	consistent_hash_globals->global_string = NULL;
}
*/
/* }}} */

/* {{{ PHP_MINIT_FUNCTION
 */
PHP_MINIT_FUNCTION(consistent_hash)
{
	/* If you have INI entries, uncomment these lines 
	REGISTER_INI_ENTRIES();
	*/
	le_chash = zend_register_list_destructors_ex(NULL, NULL, "consistent_hash", module_number);
	return SUCCESS;
}
/* }}} */

/* {{{ PHP_MSHUTDOWN_FUNCTION
 */
PHP_MSHUTDOWN_FUNCTION(consistent_hash)
{
	/* uncomment this line if you have INI entries
	UNREGISTER_INI_ENTRIES();
	*/
	return SUCCESS;
}
/* }}} */

/* Remove if there's nothing to do at request start */
/* {{{ PHP_RINIT_FUNCTION
 */
PHP_RINIT_FUNCTION(consistent_hash)
{
	MAKE_STD_ZVAL(nearest_rid);
	return SUCCESS;
}
/* }}} */

/* Remove if there's nothing to do at request end */
/* {{{ PHP_RSHUTDOWN_FUNCTION
 */
PHP_RSHUTDOWN_FUNCTION(consistent_hash)
{
	FREE_ZVAL(nearest_rid);
	return SUCCESS;
}
/* }}} */

/* {{{ PHP_MINFO_FUNCTION
 */
PHP_MINFO_FUNCTION(consistent_hash)
{
	php_info_print_table_start();
	php_info_print_table_header(2, "consistent_hash support", "enabled");
	php_info_print_table_end();

	/* Remove comments if you have entries in php.ini
	DISPLAY_INI_ENTRIES();
	*/
}
/* }}} */


/* Remove the following function when you have succesfully modified config.m4
   so that your module can be compiled into PHP, it exists only for testing
   purposes. */

/* Every user-visible function in PHP should document itself in the source */
/* {{{ proto string confirm_consistent_hash_compiled(string arg)
   Return a string to confirm that the module is compiled in */
PHP_FUNCTION(confirm_consistent_hash_compiled)
{
	char *arg = NULL;
	int arg_len, len;
	char *strg;

	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &arg, &arg_len) == FAILURE) {
		return;
	}

	len = spprintf(&strg, 0, "Congratulations! You have successfully modified ext/%.78s/config.m4. Module %.78s is now compiled into PHP.", "consistent_hash", arg);
	RETURN_STRINGL(strg, len, 0);
}
/* }}} */

/*{{{ consistent_hash_init*/
PHP_FUNCTION(consistent_hash_init)
{
	consistent_hash_table_node * ht_node;
	zval* input;
	zend_bool persistent;
	char * id_str;
	uint id_len = 0;
	uint id_len_default;
	uint replicas;

	replicas = CONSISTENT_HASH_REPLICAS;
	persistent = CONSISTENT_HASH_TABLE_PERSISTENT;
	id_len_default = strlen(CONSISTENT_HASH_TABLE_IDENTIFIER);
 	id_str = emalloc_rel(id_len_default + 1);	
	memcpy(id_str, CONSISTENT_HASH_TABLE_IDENTIFIER, id_len_default);

	if(zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a|bsl", &input, &persistent, &id_str, &id_len, &replicas) == FAILURE){
		php_error_docref(NULL TSRMLS_CC, E_ERROR, "Get argument error!");
	}
	if(persistent){
		if(id_len == 0){
			php_error_docref(NULL TSRMLS_CC, E_ERROR, "The persistent parameter was set to be true, and the identifier parameter must be set to be a unique const string!");
		}
	}
	ht_node = consistent_hash_init_impl(input, persistent, id_str, replicas);
	//Z_ARRVAL_P(return_value) = ht_node->ht;
	ZEND_REGISTER_RESOURCE(return_value, ht_node, le_chash);
	//store the nearst resource.
	Z_LVAL_P(nearest_rid) = Z_LVAL_P(return_value);
	Z_TYPE_P(nearest_rid) = Z_TYPE_P(return_value);
}

/*}}}*/

/*{{{consistent_hash_lookup*/
PHP_FUNCTION(consistent_hash_lookup)
{
	zval * rid, *z_hash;
	char* key_str, *hash_value;
	int len;
	long id;
	rid = nearest_rid; //default.
	consistent_hash_table_node * ht_node;
	if(zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|r", &key_str, &len, &rid) == FAILURE){
		php_error_docref(NULL TSRMLS_CC, E_ERROR, "Get argument error!");
	}
	if(Z_TYPE_P(rid) != IS_RESOURCE){
		php_error_docref(NULL TSRMLS_CC, E_ERROR, "Get hash table resource error!");
	}
	ZEND_FETCH_RESOURCE(ht_node, consistent_hash_table_node*, &rid, -1, le_chash_name, le_chash);
	if(!(z_hash = consistent_hash_lookup_impl(ht_node, key_str))){
		RETURN_FALSE;
		return;
	}
	//RETURN_LONG(ht_node->ht->nNumOfElements);
	//RETURN_LONG(z_hash);
	RETURN_STRINGL(Z_STRVAL_P(z_hash), Z_STRLEN_P(z_hash), 1);
}
/*}}}*/
/* The previous line is meant for vim and emacs, so it can correctly fold and 
   unfold functions in source code. See the corresponding marks just before 
   function definition, where the functions purpose is also documented. Please 
   follow this convention for the convenience of others editing your code.
*/


/*
 * Local variables:
 * tab-width: 4
 * c-basic-offset: 4
 * End:
 * vim600: noet sw=4 ts=4 fdm=marker
 * vim<600: noet sw=4 ts=4
 */
